<?php
class NICED_Transaction
{
    protected $database;
   
    protected $isValid = false;

    protected $errorMessage;
    
    protected $errorCode;

    public function __construct(&$database)
    {
        $this->database = &$database;
    }

    public function begin()
    {
         return $this->endTxn();
    }

    public function commit()
    {
        return $this->endTxn();
    }
   
    public function rollback()
    {
        return $this->endTxn();
    }
    
    protected function endTxn($sql = '')
    {
        if (!$this->isValid)
        {
            return false;
        }

        $this->isValid = false;

        if ($sql !== '')
        {
            $result = &$this->database->query($sql);

            return $result->isSuccess();
        }

        return true;
    }

    public function query($sql)
    {
        if (!$this->isValid)
        {
            return $this->database->query(null);
        }

        $result = &$this->database->query($sql);

        if (!$result->isSuccess())
        {
            $this->setError($result->getErrormessage(), $result->getErrorcode());
            $this->rollback();
        }

        return $result;
    }
    
    public function isSuccess()
    {
        return $this->isValid;
    }

	public function close()
	{
	}
	public function __destruct()
	{
	
	}

    public function getErrorMessage()
    {
        return $this->errorMessage;
    }

    public function getErrorCode()
    {
        return $this->errorCode;
    }
    
    public function getError()
    {
        return array('message' => $this->getErrormessage(), 'code' => $this->getErrorcode());
    }

    
    public function setError($message, $code)
    {
        $this->errorMessage = $message;
        $this->errorCode    = $code;   
    }
}

class NICED_MysqlTransaction extends NICED_Transaction
{
    public function __construct(&$database)
    {
        parent::__construct($database);
    }
    
    public function begin()
    {
         //$result             = $this->database->query('BEGIN');
        //mysql corana not support begin statement 
         $result             = $this->database->query('set autocommit=0');
         $this->isValid      = $result->isSuccess();
		 $this->setError($result->getErrormessage(), $result->getErrorcode());

         return $this->isValid;
    }

    public function commit()
    {
        $bool = $this->endTxn('COMMIT');
        $result  = $this->database->query('set autocommit=1');

        return $bool;
    }
    
    public function rollback()
    {
        $bool = $this->endTxn('ROLLBACK');
        $result  = $this->database->query('set autocommit=1');

        return $bool;
    }

}//end class
